export interface QRcodeType {
  type: string,
  startTime: string,
  endTime: string
}

// 将二进制文件下载
export const downloadFile = (blob: Blob, name: string | null, type: string) => {
  const a = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  a.href = href
  a.download = `${name}${type}`
  document.body.appendChild(a)
  a.click()
  // a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window})); // 兼容火狐
  document.body.removeChild(a)
  window.URL.revokeObjectURL(href)
}

// base64转为blob
export const base64ToBlob = (base64: string) => {
  const parts = base64.split(';base64,')
  const contentType = parts[0].split(':')[1]
  const raw = window.atob(parts[1])
  const rawLength = raw.length
  const uint8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; i++) {
    uint8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uint8Array], { type: contentType })
}

// 在二维码中间添加文字
export const handeleQRCode = (options: QRcodeType, imgData: any) => {
  return new Promise((resolve, reject) => {
    // const canvas = document.getElementById('canvas')
    // const canvas = <HTMLCanvasElement>document.createElement('canvas')
    const canvas: HTMLCanvasElement = document.createElement('canvas')
    canvas.setAttribute('width', '460')
    canvas.setAttribute('height', '460')
    const ctx: CanvasRenderingContext2D = canvas.getContext('2d')! // 一定不能少了“！”，作用：告诉ts这个值不是null或者undefined

    ctx.fillStyle = '#eee'
    ctx.fillRect(0, 0, 460, 460) // 画布大小

    const imgage = new Image()
    imgage.onload = () => {
      ctx.drawImage(imgage, 100, 100, 260, 260) // 二维码的位置

      // 设置字体
      ctx.font = '20px 微软雅黑 bolder' // 设置字体颜色
      ctx.fillStyle = '#000'
      ctx.fillText('使用微信/支付宝扫描', 65, 80) // 添加文字和位置
      ctx.fillStyle = 'red'
      ctx.fillText(`${options.type}`, 255, 80)
      ctx.fillStyle = '#000'
      ctx.fillText('二维码', 337, 80)
      ctx.font = '17px 微软雅黑 bolder'
      // ctx.textAlign = 'center'
      ctx.fillText(`生效时间：${options.startTime}`, 100, 395)
      ctx.fillText(`至 ${options.endTime}`, 140, 420)
      resolve(canvas.toDataURL('image/jpeg'))
    }
    imgage.src = imgData
  })
}

// 地址转文件【url = https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.niutuku.com%2Fdesk%2F1208%2F1300%2Fntk-1300-31979.jpg&refer=http%3A%2F%2Fimg2.niutuku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666831510&t=41eb22d71726307aad6570548021ca15】
export const urlToFile = (url: string) => {
  return new Promise((resolve) => {
    let blob = null
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = () => {
      if (xhr.status === 200) {
        blob = xhr.response
        const file = new File([blob], `file.${xhr.response.type.match(/\/(\S*)/)[1]}`, { type: xhr.response.type })
        resolve(file)
        // resolve(xhr.response)
      }
    }
    xhr.send('file=test.webp')
    // xhr.send()
  })
}
